import React from 'react'
import { routerItems } from '@/router';
import { matchRoute } from '@/router/match';
import { Navigate, useLocation } from 'react-router-dom';
import { connect } from 'react-redux'
import { getCache } from '@/utils/session';

const AuthRouter = (props: { children: JSX.Element, token: string }) => {
    let token = getCache('token') || props.token;
    let location = useLocation();
    let { pathname } = location;
    let isMatch = matchRoute(pathname, routerItems())
    if (token || isMatch?.meta?.isAuth) {
        return props.children
    } else {
        return <Navigate to="/login" />
    }
}

const mapStateToProps = (state: { Global: { token: string } }) => {
    return {
        token: state.Global.token
    }
}

export default connect(mapStateToProps)(AuthRouter)
